﻿using System;
using System.Globalization;
using Microsoft.Practices.CompositeUI.Properties;
using Microsoft.Practices.CompositeUI.Utility;

namespace Microsoft.Practices.CompositeUI.UIElements
{
    /// <summary>
    /// 	Support class to simplify creation of <see cref = "IUIElementAdapter" />-derived classes.
    /// </summary>
    public abstract class UIElementAdapter<TUIElement> : IUIElementAdapter
    {
        #region Implementation of IUIElementAdapter

        /// <summary>
        /// 	Adds a UI Element.
        /// </summary>
        /// <param name = "uiElement">The UI element to add.</param>
        /// <returns>The added UI element.</returns>
        public object Add(object uiElement)
        {
            Guard.ArgumentNotNull(uiElement, "uiElement");
            var element = GetTypedElement(uiElement);
            return Add(element);
        }

        /// <summary>
        /// 	Removes a UI Element.
        /// </summary>
        /// <param name = "uiElement">The UI element to remove.</param>
        public void Remove(object uiElement)
        {
            Guard.ArgumentNotNull(uiElement, "uiElement");
            var element = GetTypedElement(uiElement);
            Remove(element);
        }

        #endregion

        #region Add & Remove

        /// <summary>
        /// 	Adds a UI Element.
        /// </summary>
        /// <param name = "uiElement"></param>
        /// <returns></returns>
        protected abstract TUIElement Add(TUIElement uiElement);

        /// <summary>
        /// 	Removes a UI Element.
        /// </summary>
        /// <param name = "uiElement">The UI Element to remove.</param>
        protected abstract void Remove(TUIElement uiElement);

        #endregion

        #region Get Typed Element

        private TUIElement GetTypedElement(object uiElement)
        {
            if (!(uiElement is TUIElement))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.UIElementNotCorrectType, typeof (TUIElement)));
            }
            return (TUIElement) uiElement;
        }

        #endregion
    }
}